const  ipc = require('electron').ipcRenderer
const RuleApi = require('../dist/components/resource/rule-api').RuleApi.prototype;
const ConfigApi = require('../dist/components/resource/conf-api').ConfApi.prototype;
const SinaApi = require('../dist/components/api/Sina').Sina.prototype;
new Vue({
    el:'#app',
    data: {
        ruleHandler: null,
        configHandler: null,
        sinaHandler: null,
        headerMenuBar: 'RULE', // 顶部菜单枚举
        sharesSearchKey: '', // 下拉检索框关键字
        form: { // 规则表单信息
            ruleName: '', // 规则名称
            sharesName: '', // 名称
            sharesCode: '', // 代码
            ruleType: 0, // 规则类型
            ruleValue: 0, // 规则阈值
            repeatNot: '', // 是否重复通知
            id: ''
        },
        showForm: false,
        configForm: { // 基础配置信息
            intervalMs: 10000,
            hideNotifactionDetail: false,
            notificationTemplate: '',
            status: 'ON'
        },
        searchTimer: null, // 检索延时器
        searchSelectVisiable: false, // 检索下拉框是否可见
        searchSelectOptions: [{}], // 检索下拉框选项
        rules: [{}], // 右侧规则列表
        selectedRulesId: '', // 右侧规则列表当前选中规则id
        selectedSharesCode: ''
    },
    methods: {
        /**
         * 顶部菜单栏切换
         * @param {} key 
         */
        headerMenu(key) {
            if (key === 'config') {
                this.loadConfig();
            }
            this.headerMenuBar = key
        },
        resetForm() {
            for (let key in this.form){
                this.form[key] = ''
            }
            this.selectedRulesId = ''
            this.sharesSearchKey = ''
            this.selectedSharesCode = ''
        },

        /**
         *  规则新建 & 更新
         * @param {*} ruleItem 
         */
        saveRule() {
            if (!this.form.ruleName) {
                alert('请填入自定义的规则名称！')
                return
            }
            if (!this.form.sharesName || !this.form.sharesCode) {
                alert('请通过下拉选择正确的监控资源！')
                this.sharesSearchKey = ''
                this.form.sharesCode = ''
                this.form.sharesName = ''
                return
            }

            if (!this.form.ruleType) {
                alert('请选择监控类型！')
                return
            }
            
            if (!this.form.ruleValue || this.form.ruleValue <= 0) {
                alert('请填入有效的监控阈值！')
                return
            }

            let newItem = JSON.parse(JSON.stringify(this.form))
            this.ruleHandler.update(newItem)
            this.refreshRules()
            this.showForm = false
        },

        searchShares(key) {
            if (this.searchTimer != null) {
                clearTimeout(this.searchTimer);
            }
            setTimeout(() => {
                this.sinaHandler.keywordSearch(key, (data) => {
                    if (data.length > 0) {
                        this.searchSelectOptions = Object.assign([], data);
                    }
                });
            }, 500);
        },

        onSearchInputblur() {
            setTimeout(() => {
                this.searchSelectVisiable = false 
            }, 200);
        },

        onSearchInputFocus() {
            this.searchSelectVisiable = true
        },

        onSearchSelected(sharesName, sharesCode) {
            this.form.sharesCode = sharesCode
            this.form.sharesName = sharesName
            this.sharesSearchKey = sharesName
        },
        onSelectRules(item) {
            for(let key in this.form) {
                this.form[key] = item[key];
            }
            this.sharesSearchKey = this.form.sharesName
            this.selectedRulesId = this.form.id
            this.selectedSharesCode = this.form.sharesCode
        },
        getGif() {
            return `http://image.sinajs.cn/newchart/min/n/${this.selectedSharesCode}.gif`;
        },

        onOperationAdd() {
            this.resetForm()
            this.showForm = true
        },

        onOperationEdit() {
            // this.resetForm();
            this.showForm = true
        },
        
        cancel() {
            this.resetForm();
            this.showForm = false
            this.selectFirst()
        },

        onOperationRemove() {
            let confirm = window.confirm(`确认删除规则”${this.form.ruleName}“`)
            if (confirm) {
                this.ruleHandler.remove(this.form.id)
                this.resetForm()
                this.refreshRules()
            }
        },

        onOperationRefresh() {

        },

        refreshRules() {
            this.rules = Object.assign([], this.ruleHandler.getAll())
            this.selectFirst()
            ipc.send('RULE_UPDATE')
        },
        selectFirst() {
            if (this.rules.length > 0) {
               this.onSelectRules(this.rules[0])
            }
        },

        loadConfig() {
            let config = this.configHandler.getAll()
            this.configForm = Object.assign({}, config);
        }
    },
    watch: {
        sharesSearchKey(newVal) {
            this.searchShares(newVal)
        },
        configForm: {
            handler(newVal,oldVal) {
                this.configHandler.update(newVal);
                ipc.send('CONFIG_UPDATE')
            },
            deep: true
        }
    },
    mounted() {
        this.ruleHandler = RuleApi
        this.configHandler = ConfigApi
        this.sinaHandler = SinaApi
        this.refreshRules()
        this.loadConfig()
        ipc.on('CONTEXT_MENU', (e, type) => {
            if (type != 'ON' || type != 'OFF') {
                console.log(type)
                this.headerMenuBar = type
            }
        })
        ipc.on('CONFIG_UPDATE', () => {
            this.loadConfig();
        });
    }
});